package com.company.woye.checkmakesure;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.checkmakesure.adapter.MakeSureListviewAdapter;
import com.company.woye.checkmakesure.bean.MakeSureBean;
import com.company.woye.taiorcheckSize.TaiorCheckSizeActivity;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.DataUtils;
import com.company.woye.utils.Toaster;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.company.woye.MyApplication.UrlCut;

public class MakeSureCheckActivity extends BaseActivity {

    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_on_package_sure)
    TextView tvOnPackageSure;
    @BindView(R.id.tv_on_package_search)
    TextView tvOnPackageSearch;
    @BindView(R.id.tv_on_package_start_time)
    TextView tvOnPackageStartTime;
    @BindView(R.id.tv_on_package_end_time)
    TextView tvOnPackageEndTime;
    @BindView(R.id.sp_on_package_deptname)
    Spinner spOnPackageDeptname;
    @BindView(R.id.sp_on_package_factory)
    Spinner spOnPackageFactory;
    @BindView(R.id.sp_on_package_grop)
    Spinner spOnPackageGrop;
    @BindView(R.id.sp_on_package_state)
    Spinner spOnPackageState;
    @BindView(R.id.ed_on_package_person)
    TextView edOnPackagePerson;
    @BindView(R.id.ed_on_package_danbian)
    EditText edOnPackageDanbian;
    @BindView(R.id.lv_on_package_summary)
    ListView lvOnPackageSummary;
    @BindView(R.id.ll_on_package_summary)
    LinearLayout llOnPackageSummary;
    @BindView(R.id.rl)
    RelativeLayout rl;
    String FormType = getClass().getSimpleName();
    @BindView(R.id.tv_zdr)
    TextView tvZdr;
    @BindView(R.id.tv)
    TextView tv;
    private String bigDept = "", deptName = "", cJname = "", LoginUserNo = "", cDate = "", inputId, inputMan, lsxName = "", EmpName = "", EmpYgh = "";
    private String TimeType = "";//1是开始时间  2 是结束时间
    private JSONArray deptJsonarray, cJnameJsonarray, LsxNameJsonArray, masterJSONArray;
    private final int MSG_FIND_DEPT = 9001;
    private final int MSG_FIND_CJNAME = 9002;
    private final int MSG_FIND_LSXNAME = 9003;
    private final int MSG_FIND_LIST = 9004;
    private final int MSG_ERROR = 9007;
    private List<String> deptNameList=new ArrayList<>(), cJnameList=new ArrayList<>(), LsxNameList=new ArrayList<>(), taskStateList=new ArrayList<>();
    private ArrayAdapter<String> deptAdapter, cjNameAdapter, lsxNameAdapter, taskStateAdapter;
    private MakeSureListviewAdapter adapter;
    private List<MakeSureBean> dataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_sure_check);
        ButterKnife.bind(this);
        cJname = getIntent().getStringExtra("cjName");
        deptName= getIntent().getStringExtra("bmName");
        lsxName = getIntent().getStringExtra("lsx");
        bigDept = getIntent().getStringExtra("bigDept");
        inputMan = getIntent().getStringExtra("inputMan");
        inputId = getIntent().getStringExtra("inputId");
        Log.e("传递过来","cJname:"+cJname+";deptName:"+deptName+";lsxName"+lsxName);
        edOnPackagePerson.setText(inputMan);

        LoginUserNo = MyApplication.curLoginUserNo;
        tvOnPackageStartTime.setText(DataUtils.getNowData());
        tvOnPackageEndTime.setText(DataUtils.getNowData());


        adapter = new MakeSureListviewAdapter(this, dataList);
        lvOnPackageSummary.setAdapter(adapter);

        lvOnPackageSummary.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /**
                 * {
                 *   "bbm": "制衣二部",
                 *   "bmName": "制衣二部(1)",
                 *   "dh":"210107220211100423",
                 *   "cc": 9,
                 *   "ccxh": 11,
                 *   "cjName": "裁剪一工场",
                 *   "hyh": "NK43332-D09AY",
                 *   "kdcs": 1,
                 *   "lsx": "1-2",
                 *   "mkbl": "S:3XL=4:4",
                 *   "token": "7e0daaaed1a1543727122788a4e5398e7c23e88b075a32e3922a6d96b5642db9"
                 * }
                 */
                Intent intent = new Intent(MakeSureCheckActivity.this, MakeSureDetailActivity.class);
                intent.putExtra("data", dataList.get(position));
                if (deptNameList != null && deptNameList.size() > 0) {
                    intent.putExtra("bmName", spOnPackageDeptname.getSelectedItem().toString());
                } else {
                    intent.putExtra("bmName", "");
                }
                if (cJnameList != null && cJnameList.size() > 0) {
                    intent.putExtra("cjName", spOnPackageFactory.getSelectedItem().toString());
                } else {
                    intent.putExtra("cjName", "");
                }
                startActivity(intent);
            }
        });

        //任务状态
        taskStateList = new ArrayList<>();
        taskStateList.add("全部");
        taskStateList.add("未完成");
        taskStateList.add("已完成");
        taskStateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, taskStateList);
        spOnPackageState.setAdapter(taskStateAdapter);

        //获取部门
        getDepaName();
    }

    private void getLsxName() {
        String sqlFindLsxName = "EXEC  AGV_Basic_GetLsxName @UserNo ='" + LoginUserNo + "'" + ", @cj_name ='" + (cJnameList.size() > 0 ? spOnPackageFactory.getSelectedItem() : "") + "', @FormType ='" + FormType + "'" + ", @OperType ='GetLsxName'";
        ReadSQLData(sqlFindLsxName, "LsxName");
    }

    private void getDepaName() {
        String sqlFindDept = "EXEC  AGV_Basic_GetBbmName @UserNo ='" + LoginUserNo + "'" + ", @FormType ='" + FormType + "'" + ", @OperType ='GetBbmName'";
        ReadSQLData(sqlFindDept, "dept");
    }

    private void getCjName() {
        String sqlFindcJname = "EXEC  AGV_Basic_GetSewCjName  @bmName='"+(deptNameList.size() > 0 ? spOnPackageDeptname.getSelectedItem() : "")+"', @UserNo ='" + LoginUserNo + "'" + ", @FormType ='" + FormType + "'" + ", @OperType ='GetSewCjName'";
        ReadSQLData(sqlFindcJname, "cJname");

    }

    private void getList() {
        String sqlFindcJname = "EXEC [CutPAD_GetCheckWorkOrders] @bbm='" + spOnPackageDeptname.getSelectedItem() + "',@Factory='" + spOnPackageFactory.getSelectedItem()
                + "',@lsx='" + spOnPackageGrop.getSelectedItem() + "',@state='" + spOnPackageState.getSelectedItem() + "',@StartDate='" + tvOnPackageStartTime.getText().toString() + "',@EndDate='" + tvOnPackageEndTime.getText().toString() + "'";
        ReadSQLData(sqlFindcJname, "list");
    }

    private void ReadSQLData(String sql, String type) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(UrlCut, sql);
                    System.out.print("----返回结果：" + jsonArray);
                    //部门
                    if (type.equals("dept")) {
                        deptJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_DEPT;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //车间
                    if (type.equals("cJname")) {
                        cJnameJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_CJNAME;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //组别
                    if (type.equals("LsxName")) {
                        LsxNameJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_LSXNAME;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //列表
                    if (type.equals("list")) {
                        masterJSONArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_LIST;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }

                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //获取部门
                case MSG_FIND_DEPT:
                    if (deptJsonarray != null && deptJsonarray.length() > 0) {
                        deptNameList = new ArrayList<>();
                        for (int i = 0; i < deptJsonarray.length(); i++) {
                            try {
                                deptNameList.add(deptJsonarray.optJSONObject(i).get("BbmName").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        deptAdapter = new ArrayAdapter<String>(MakeSureCheckActivity.this, android.R.layout.simple_dropdown_item_1line, deptNameList);
                        spOnPackageDeptname.setAdapter(deptAdapter);
                        for (int i = 0; i < deptNameList.size(); i++) {
                            if (deptNameList.get(i).equals(deptName)) {
                                spOnPackageDeptname.setSelection(i);
                            }
                        }
                        spOnPackageDeptname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                //获取车间
                                getCjName();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                    //获取车间
                    getCjName();
                    break;
                //获取车间
                case MSG_FIND_CJNAME:
                    if (cJnameJsonarray != null && cJnameJsonarray.length() > 0) {
                        cJnameList = new ArrayList<>();
                        for (int i = 0; i < cJnameJsonarray.length(); i++) {
                            try {
                                cJnameList.add(cJnameJsonarray.optJSONObject(i).get("CjName").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        cjNameAdapter = new ArrayAdapter<String>(MakeSureCheckActivity.this, android.R.layout.simple_dropdown_item_1line, cJnameList);
                        spOnPackageFactory.setAdapter(cjNameAdapter);
                        for (int i = 0; i < cJnameList.size(); i++) {
                            if (cJnameList.get(i).equals(cJname)) {
                                spOnPackageFactory.setSelection(i);
                            }
                        }
                        spOnPackageFactory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                //获取流水线
                                getLsxName();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                    //获取流水线
                    getLsxName();
                    break;

                //获取组别
                case MSG_FIND_LSXNAME:

                    if (LsxNameJsonArray != null && LsxNameJsonArray.length() > 0) {
                        LsxNameList = new ArrayList<>();
                        for (int i = 0; i < LsxNameJsonArray.length(); i++) {
                            try {
                                LsxNameList.add(LsxNameJsonArray.optJSONObject(i).get("lsx").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        lsxNameAdapter = new ArrayAdapter<String>(MakeSureCheckActivity.this, android.R.layout.simple_dropdown_item_1line, LsxNameList);
                        spOnPackageGrop.setAdapter(lsxNameAdapter);
                        for (int i = 0; i < LsxNameList.size(); i++) {
                            if (LsxNameList.get(i).equals(lsxName)) {
                                spOnPackageGrop.setSelection(i);
                            }
                        }
                        spOnPackageGrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                //获取列表
                              getList();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                    //获取列表
                    getList();
                    break;
                //获取列表
                case MSG_FIND_LIST:
                    System.out.println("MSG_FIND_LIST");
                    if (masterJSONArray != null && masterJSONArray.length() > 0) {
                        Gson gson = new Gson();
                        dataList.clear();
                        dataList.addAll(gson.fromJson(String.valueOf(masterJSONArray), new TypeToken<List<MakeSureBean>>() {
                        }.getType()));
                        //获取明细;
                        adapter.notifyDataSetChanged();
                    }
                    break;

                case MSG_ERROR:
                    Toaster.showLong(MakeSureCheckActivity.this, "连接数据库失败");
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public int setLayoutId() {
        return R.layout.activity_make_sure_check;
    }

    @Override
    public void initView() {


    }

    @OnClick({R.id.tv_on_package_search, R.id.tv_on_package_back, R.id.iv_on_package_back, R.id.tv_sure, R.id.tv_on_package_start_time, R.id.tv_on_package_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_on_package_back:
            case R.id.tv_on_package_back:
                finish();
                break;
            case R.id.tv_sure:
                break;
            case R.id.tv_on_package_search:
                getList();
                break;
            case R.id.tv_on_package_start_time:
                TimeType = "1";
                showDatePickDlg();
                break;
            case R.id.tv_on_package_end_time:
                TimeType = "2";
                showDatePickDlg();
                break;
        }
    }

    public void showDatePickDlg() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(MakeSureCheckActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String month;
                if ((monthOfYear + 1) < 10) {
                    month = "0" + (monthOfYear + 1);
                } else {
                    month = (monthOfYear + 1) + "";
                }
                if (TimeType.equals("1")) {
                    tvOnPackageStartTime.setText(year + "-" + (month) + "-" + dayOfMonth);
                } else if (TimeType.equals("2")) {
                    tvOnPackageEndTime.setText(year + "-" + (month) + "-" + dayOfMonth);
                }
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }
}
